import { Controller, Post, Body, Inject, Res } from '@nestjs/common';
import { ChatRequest } from './dto/chat-message.dto';
import { HttpService } from '@nestjs/axios';
import { lastValueFrom } from 'rxjs';
import { Response } from 'express';
import { GptResponse } from './types/gpt.types';
import { Readable } from 'stream';
import { AxiosResponse } from 'axios';

@Controller('gpt')
export class GptController {
  constructor() {}

  @Inject()
  private httpService: HttpService;

  @Post()
  async chat(@Body() body: ChatRequest, @Res() res: Response) {
    const chatRequest = {
      model: 'ep-20250106193712-85mtk',
      messages: body.content,
      stream: true,
    };

    const response = this.httpService.post<GptResponse>(
      'http://ark.cn-beijing.volces.com/api/v3/chat/completions',
      chatRequest,
      {
        headers: {
          Authorization: 'Bearer 81aa9d96-0b3f-46c8-a57b-ca8b2aca9b1a',
        },
        responseType: 'stream',
      },
    );

    // 处理流数据
    // @ts-expect-error stream
    const stream: AxiosResponse<Readable> = await lastValueFrom(response);
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    stream.data.on('data', (chunk: Buffer) => {
      // 处理接收到的数据并发送给客户端
      const lines = chunk.toString().split('\n');
      lines.forEach((line) => {
        if (line && !line.startsWith('data: [DONE]')) {
          const data = JSON.parse(line.slice(6)) as GptResponse;
          const result = data?.choices?.[0].delta?.content as string;
          // if (result !== `\n\n`) {
          // 必须加格式，艹了
          res.write(`data:${JSON.stringify({ data: result })}\n\n`);
          // console.log(result);
          // }
        }
      });
    });

    stream.data.on('end', () => {
      // 结束SSE流
      res.end();
    });

    stream.data.on('error', () => {
      res.end();
    });
    // const data = response.data as GptResponse;
    // const result = data.choices[0].message;
    // return result;
  }
}
